﻿using System;
using System.Collections;
using System.IO;
using Assets.Scripts.Commom;
using Assets.Scripts.Net;
using Assets.Scripts.Tool;
using Assets.Scripts.UI.Panel;
using RenderHeads.Media.AVProVideo;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Scripts.UI.Item
{
    /// <summary>
    /// 播放器的播放模式
    /// </summary>
    public enum PlayerMode
    {
        Normal,//普通
        FullScreen,//全屏
    }
    public class QueVideoItem:UIBase<QueAudioItem>
    {

        public Button PlayButton;
        public Button PauseButton;
        public Button FSButton;
        public Button FSExitButton;
        public VideoSeekBar VideoSeekBar;
        public MediaPlayer MediaPlayer; 
        public Transform VideoDisplay;

        private string videoPath { get; set; }
        private string tempPath { get; set;}//视频播放的零时路径
        private bool isLoaded { get; set; }//是否已经加载视频
        private static int index { get; set; }//视频播放的次数

        protected override UIType UIType
        {
            get { return UIType.Item;}
        }

        protected override void InitOnAwake()
        {
            AutoFindComponent(transform,true);
            MediaPlayer.Events.AddListener(OnVideoEvent);
            VideoSeekBar.Init(MediaPlayer);
            PlayButton.onClick.AddListener(OnPlayButtonClick);
            PauseButton.onClick.AddListener(OnPauseButtonClick);
            FSButton.onClick.AddListener(OnFSButtonClick);
            FSExitButton.onClick.AddListener(OnFSExitButtonClick);
            if(ExamPanel._Instance!=null) ExamPanel._Instance.VideoItems.Add(this);
        }

        /// <summary>
        /// 初始化方法
        /// </summary>
        public void Init(string videoPath)
        {
            this.videoPath = videoPath;
        }

        /// <summary>
        /// Video事件
        /// </summary>
        /// <param name="mp"></param>
        /// <param name="et"></param>
        /// <param name="errorCode"></param>
        public void OnVideoEvent(MediaPlayer mp, MediaPlayerEvent.EventType et, ErrorCode errorCode)
        {
            switch (et)
            {
                case MediaPlayerEvent.EventType.ReadyToPlay:
                    break;
                case MediaPlayerEvent.EventType.Started:
                    if (tempPath != null)
                    {
                        Debug.Log("删除临时的视频");
                        File.Delete(tempPath);
                        tempPath = null;
                    }
                    break;
                case MediaPlayerEvent.EventType.FirstFrameReady:
                    break;
                case MediaPlayerEvent.EventType.FinishedPlaying:
                    IsPlayVideo(false);
                    break;
            }
            Debug.Log("视频的事件：" + et);
            Debug.Log("错误码：" + errorCode);
        }

        /// <summary>
        /// 视频播放
        /// </summary>
        private void OnPlayButtonClick()
        {
            if(ExamPanel._Instance!=null)
                ExamPanel._Instance.StopMediaPlay();
            IsPlayVideo(true);
            if (isLoaded)
            {
                MediaPlayer.Control.Play();
                return;
            }   
            isLoaded = true;
            if (ExamPanel._Instance != null)//如果考试界面的单例为空，则表示在CollectPanel
            {
                ExamPanel._Instance.StartCoroutine(LoadingVideo(PlayVideo, videoPath));    
            }
            else
            {
                CollectPanel._Instance.StartCoroutine(LoadingVideo(PlayVideo, videoPath));
            }
        }

        IEnumerator LoadingVideo(Action<string> action, string mediaPath)
        {
            string path = "file:///"+NetConfig.NET_RES_PATH+ mediaPath;
            Debug.Log("path:" + path);
            using (WWW www = new WWW(path))
            {
                yield return www;
                if (www.isDone && www.error == null)
                {
                    byte[] bytes = www.bytes;
                    tempPath = GetTempPath(NetConfig.NET_RES_PATH + mediaPath);
                    Debug.Log("tempPath:"+tempPath);
                    File.WriteAllBytes(tempPath, EnCriptionTool.Decryption(bytes));
                    if (action != null) action(tempPath);
                }
                else
                {
                    Debug.LogWarning(www.error);
                }
            }
        }

        /// <summary>
        /// 视频暂停
        /// </summary>
        private void OnPauseButtonClick()
        {
            if (MediaPlayer && MediaPlayer.Control != null)
            {
                MediaPlayer.Control.Pause();
                IsPlayVideo(false);
            }
        }

        /// <summary>
        /// 全屏按钮的点击事件
        /// </summary>
        public void OnFSButtonClick()
        {
            FSExitButton.gameObject.SetActive(true);
            FSButton.gameObject.SetActive(false);
            Transform parent = ExamPanel._Instance != null
                ? ExamPanel._Instance.FullScreenParent
                : ExerciseDetailPanel.FullScreenParent;
            parent.gameObject.SetActive(true);
            VideoDisplay.SetParent(parent);
            SetRectTransformInfo(VideoDisplay);
            //设置handle的大小
            Transform handle = VideoSeekBar.transform.Find("Handle Slide Area/Handle");
            handle.localScale = Vector3.one*1.8f;
        }

        /// <summary>
        /// 退出全屏按钮的点击事件
        /// </summary>
        public void OnFSExitButtonClick()
        {
            FSExitButton.gameObject.SetActive(false);
            FSButton.gameObject.SetActive(true);
            Transform parent = ExamPanel._Instance != null
                ? ExamPanel._Instance.FullScreenParent
                : ExerciseDetailPanel.FullScreenParent;
            parent.gameObject.SetActive(false);
            VideoDisplay.SetParent(transform.Find("Background"));
            SetRectTransformInfo(VideoDisplay);
            Transform handle = VideoSeekBar.transform.Find("Handle Slide Area/Handle");
            handle.localScale = Vector3.one;
        }

        private void IsPlayVideo(bool isPlay)
        {
            VideoSeekBar.isPlay = true;
            PauseButton.gameObject.SetActive(isPlay);
            PlayButton.gameObject.SetActive(!isPlay);
        }

        private string GetTempPath(string path)
        {
            index++;
            return path.Split('.')[0] + index + ".mp4";
        }

        void PlayVideo(string path)
        {
            MediaPlayer.m_VideoPath = path;
            MediaPlayer.OpenVideoFromFile(MediaPlayer.FileLocation.AbsolutePathOrURL, path, false);
            MediaPlayer.Control.Play();
        }
    }
}